package IC;

import java_cup.runtime.*;
import IC.Parser.*;
import IC.AST.*;
import java.io.*;




public class Compiler
{
	private static boolean printtokens = true;
	
	private static ICClass rootLibrary;
	private static Program root;
	private static boolean LibraryMode;
	
    public static void main(String[] args)
    {    		
    	try
    	{
    		
    		FileReader txtFile = new FileReader(args[0]);

    		Lexer scanner = new Lexer(txtFile);
			Parser parser = new Parser(scanner);
			parser.printTokens = printtokens;	///////////////////////

			Symbol parseSymbol = (Symbol) parser.parse();

			root = (Program) parseSymbol.value;
    	}
    	catch (SyntaxError syn) {
    		System.out.println(syn.toString());
    	}
    	catch (LexicalError lex) {
    		System.out.println(lex.toString());
    	}
    	catch (Exception e) {
    		throw new RuntimeException("IO Error(brutal exit" + e.toString());
    	}
    	
    	
    	for (int i = 1; i < args.length; i++)
    	{
    		String input = args[i];
    		
    		if (input.substring(0, 2).equals("-L"))
    		try
        	{
    			LibraryMode = true;
        		FileReader txtFile = new FileReader(input.substring(2));
        		Lexer scanner = new Lexer(txtFile);
    			LibraryParser parserLibrary = new LibraryParser(scanner);    		
    			Symbol parseSymbol = (Symbol) parserLibrary.parse();
    			rootLibrary = (ICClass) parseSymbol.value;
        		continue;
        	}
        	catch (SyntaxError syn) {
        		System.out.println(syn.toString());
        	}
        	catch (LexicalError lex) {
        		System.out.println(lex.toString());
        	}
        	catch (Exception e) {
        		throw new RuntimeException("IO Error(brutal exit" + e.toString());
        		}
    		
    		if (input.equals("-print-ast"))
    		{
    			if(LibraryMode)
    				root.addClass(rootLibrary);
    			//Program root = (Program) parseSymbol.value;
    			PrettyPrinter printer = new PrettyPrinter(args[0]);
    			System.out.println("Parsed " + args[0] + " successfully!");
    			System.out.println(root.accept(printer));
    			break;
    		}
    			
    		
    	}
    	
    	
    	
        	
    	
    }
}
